package com.wanho.activemq.prototype.queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 队列模式  异步消费者
 */
public class QueueAsynchronousConsumer {
    public static void main(String[] args) {
        //创建一连接工厂
        ConnectionFactory connectionFactory  = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
        try {
            //创建一个连接
            Connection connection = connectionFactory.createConnection();
            //打开连接
            connection.start();
            //创建一个回话
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //创建一个目的地Destination
            Queue queue = session.createQueue("mytestqueue");
            //创建一个消费者
            MessageConsumer consumer = session.createConsumer(queue);
            consumer.setMessageListener(new MessageListener() {

                @Override
                public void onMessage(Message message) {
                    if (message instanceof TextMessage) {
                        String text = "";
                        try {
                            text = ((TextMessage)message).getText();
                        } catch (JMSException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        System.out.println(text);
                    }

                }
            });
            System.in.read();
            //关闭
            consumer.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
